package com.jf.blog_jf04.service.impl;

import com.google.code.kaptcha.Producer;
import com.jf.blog_jf04.service.KaptchaService;
import com.jf.blog_jf04.utils.MyConstants;
import com.jf.blog_jf04.utils.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.awt.image.BufferedImage;
import java.time.Duration;

@Service
public class KaptchaServiceImpl implements KaptchaService {
    @Autowired
    private Producer producer;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public BufferedImage createKaptcha(String uuid) {
        if (!StringUtils.hasText(uuid)) {
            throw new BusinessException("uuid不能为空！");
        }
        /*生成验证码文本内容*/
        String code = producer.createText();
        /*生成图片*/
        BufferedImage bi = producer.createImage(code);
        /*存入缓存*/
        redisTemplate.opsForValue().set(MyConstants.KAPTCHA_KEY + uuid, code, Duration.ofMinutes(2));
        return bi;
    }

    @Override
    public boolean checkKaptcha(String uuid, String code) {
        String redisCode = redisTemplate.opsForValue().get(MyConstants.KAPTCHA_KEY + uuid);
        return redisCode != null && redisCode.equalsIgnoreCase(code);
    }
}
